package com.nncsys.util

import org.apache.avro.JsonProperties.Null
import org.apache.avro.Schema
import org.apache.avro.generic.{GenericDatumReader, GenericDatumWriter, IndexedRecord}
import org.apache.avro.io.{BinaryDecoder, BinaryEncoder, DatumReader, DatumWriter, DecoderFactory, EncoderFactory}

import java.io.{ByteArrayInputStream, ByteArrayOutputStream}

object AvroUtil {


  //数据层面：IndexedRecord 反序列化
  @throws[Exception]
  def getDeserialize(schema: Schema, bs: Array[Byte]): IndexedRecord = {
    val datumReader = new GenericDatumReader[IndexedRecord](schema)
    val byteArrayInputStream = new ByteArrayInputStream(bs)
    val decoder = DecoderFactory.get.directBinaryDecoder(byteArrayInputStream, null)
    datumReader.read(null, decoder)
  }

  //数据层面：IndexedRecord 序列化
  @throws[Exception]
  def getSerialized(message: IndexedRecord, schema: Schema): Array[Byte] = { //参考 io.github.agolovenko.avro.toBytes()
    val dw: DatumWriter[IndexedRecord] = new GenericDatumWriter[IndexedRecord]
    dw.setSchema(schema)
    val outputStream: ByteArrayOutputStream = new ByteArrayOutputStream
    val encoder: BinaryEncoder = EncoderFactory.get.directBinaryEncoder(outputStream, null)
    dw.write(message, encoder)
    return outputStream.toByteArray
  }

}
